package com.lottery.ruok.lottrey.activity;

import android.app.Activity;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.adapter.MyPagerAdapter;
import com.lottery.ruok.lottrey.retrofitModule.response.GetMsgResponse;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

public class NoticeDialogActivity extends Activity {
    @BindView(R.id.viewPager)
    ViewPager mVp;
    @BindView(R.id.web_title)
    TextView mWebTitle;
    @BindView(R.id.view_placeholder)
    View view_placeholder;
    @BindView(R.id.ll_indicator)
    LinearLayout mIndicators;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.tv_up)
    TextView tvUp;
    @BindView(R.id.ib_close)
    ImageButton ibClose;
    Unbinder unbinder;
    @BindView(R.id.ll_bountll_button_group)
    LinearLayout llBountllButtonGroup;
    private ArrayList<Integer> isAlertIndex = new ArrayList<>();
    private ArrayList<View> mWebViews;
    private ArrayList<GetMsgResponse> msgResponse;
    private int mCurrentPosition = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_fragment_notice);
        ButterKnife.bind(this);
        msgResponse = (ArrayList<GetMsgResponse>) getIntent().getExtras().getSerializable("notice_responses");
        setFinishOnTouchOutside(false);
        initView();
    }

    private void initView() {
        mWebViews = new ArrayList<>();
        if (tvUp.getVisibility() == View.VISIBLE && tvNext.getVisibility() == View.VISIBLE) {
            view_placeholder.setVisibility(View.VISIBLE);
        } else {
            view_placeholder.setVisibility(View.GONE);
        }
        for (int i = 0; i < msgResponse.size(); i++) {
            if ("1".equals(msgResponse.get(i).getIs_alert())) {
                mWebViews.add(getWebView(msgResponse.get(i)));
                isAlertIndex.add(i);
            }
        }
        if (isAlertIndex.size() == 1) {
            llBountllButtonGroup.setVisibility(View.GONE);
            mIndicators.setVisibility(View.GONE);
        }
        if (isAlertIndex.size() > 0) {
            mWebTitle.setText(msgResponse.get(isAlertIndex.get(0)).getTitle());
        }
        mVp.setAdapter(new MyPagerAdapter(mWebViews));

        for (int i = 0; i < mWebViews.size(); i++) {
            View indicator = new View(this);
            if (i == mCurrentPosition) {
                indicator.setBackground(getResources().getDrawable(R.drawable.bg_corners_8));
            } else {
                indicator.setBackground(getResources().getDrawable(R.drawable.bg_corners_100_17));
            }

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            lp.width = 15;
            lp.height = 15;
            if (msgResponse.size() != 1) {
                lp.setMargins(i == 0?0:20, 0, 0, 0);
            }
            indicator.setLayoutParams(lp);
            mIndicators.addView(indicator);
        }

        mVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tvUp.setVisibility(position == 0 ? View.GONE : View.VISIBLE);
                tvNext.setVisibility(position == mWebViews.size() - 1 ? View.GONE : View.VISIBLE);

                if (tvUp.getVisibility() == View.VISIBLE && tvNext.getVisibility() == View.VISIBLE) {
                    view_placeholder.setVisibility(View.VISIBLE);
                } else {
                    view_placeholder.setVisibility(View.GONE);
                }
                for (int i = 0; i < mIndicators.getChildCount(); i++) {
                    View childAt = mIndicators.getChildAt(i);
                    if (i == position) {
                        childAt.setBackground(getResources().getDrawable(R.drawable.bg_corners_8));
                    } else {
                        childAt.setBackground(getResources().getDrawable(R.drawable.bg_corners_100_17));
                    }
                    mCurrentPosition = position;
                }

                mWebTitle.setText(msgResponse.get(isAlertIndex.get(position)).getTitle());

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
       /* //设置屏幕外面点击不消失，返回键不消失
        getDialog().setCancelable(false);
        getDialog().setCanceledOnTouchOutside(false);
        getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    return true;
                }
                return false;
            }
        });*/
    }

    private WebView getWebView(GetMsgResponse msg) {
        WebView webView = new WebView(this);
        WebSettings webSettings = webView.getSettings();
        //支持缩放，默认为true。
        webSettings.setSupportZoom(false);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
        webSettings.setJavaScriptEnabled(true);
        webSettings.setBlockNetworkImage(false);
        //调整图片至适合webview的大小
//        webSettings.setUseWideViewPort(true);
//        // 缩放至屏幕的大小
        webSettings.setLoadWithOverviewMode(true);
        //设置默认编码
        webSettings.setDefaultTextEncodingName("utf-8");
        //设置自动加载图片
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setDomStorageEnabled(true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }

        webView.loadData(getHtml(msg.getContent()), "text/html; charset=UTF-8", null);

        return webView;

    }

    private String getHtml(String msg) {
        String htmlData1 = replaceImgStyle(msg);
        String imgStyle = "<style> img{ max-width:100%; height:auto;} a{color:#666666;text-decoration:none;background:#fff;}a:active{background:#fff;} a:focus{background:#fff;} a:hover{ background:#fff; color:#666666} </style>";
        htmlData1 = imgStyle + htmlData1;

        return htmlData1;
    }

    /**
     * 使用正则表达式 把html标签中的style属性全部替换成""
     */
    private String replaceImgStyle(String html) {
        String reg = "style=\"([^\"]+)\"";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(html);
        return matcher.replaceAll("");
    }

    @OnClick({R.id.tv_next, R.id.tv_up, R.id.ib_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_next:
                if (mCurrentPosition == mWebViews.size() - 1) {
                    mCurrentPosition = 0;
                    mVp.setCurrentItem(mCurrentPosition);
                } else {
                    mVp.setCurrentItem(mCurrentPosition + 1);
                }
                break;
            case R.id.tv_up:
                if (mCurrentPosition == 0) {
                    mCurrentPosition = mWebViews.size() - 1;
                }
                mVp.setCurrentItem(mCurrentPosition - 1);
                break;
            case R.id.ib_close:
                finish();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }
}
